<template>
	<view class="member_center">
		
		<view class="member_nav" v-if="topMenu">
			<u-navbar
				:title="userName"
				@rightClick="rightClick"
				:autoBack="true"
				:bgColor="bgColor"
				height="44"
				leftIconColor="#ffffff"
				titleStyle="color:#fff"
			>
			</u-navbar>
		</view>
		
		<!-- 吸顶菜单动画 需要在 member_scroll 的 nav 里添加 bgColor="transparent"
		<view class="scroll_animation" v-if="scrollMenu" :style="{height: customNavHeight + 'px;'}"></view>
		<view class="scroll_animation_back" v-if="topMenu" :style="{height: customNavHeight + 'px;'}"></view> -->
		
		<view class="member_scroll" :animation="animationData">
			<u-navbar
				leftText="返回"
				height="44"
			>
				<view
					class="u-nav-slot dflex scrollLogo aic"
					slot="left"
				>
					<u-icon name="arrow-left" size="24" @click="autoBack"></u-icon>
					<image :src="avatarSrc" mode="aspectFill" @click="noneClick"></image>
					<text class="f14 fbold u-line-1" style="max-width: 120px;" @click="noneClick">{{ userName }}</text>
					<view class="f12 fbold small_follow_button_check" @click="deleteFollower" v-if="is_followed">
						已关注
					</view>
					<view class="f12 fbold small_follow_button" @click="addFollower" v-else>
						关注+
					</view>
				</view>
			</u-navbar>
		</view>
		
		
		<view class="member_banner">
			<view class="shop_header_mask p_absolute" style="z-index: 5;"></view>
			<u-image :showLoading="true" :src="bannerSrc" :width="sysWidth" height="180"></u-image>
		</view>
		
		<view class="user_info_box">
			<view class="user_avatar" @click="openBigAvatar">
				<u-avatar :src="avatarSrc" size="75" mode="aspectFill"></u-avatar>
			</view>
			<view class="user_info">
				<view class="user_info_text" @click="gotoFollowings" :data-currentuid="userId">
					<text>{{ count_followings }}</text>
					<text>关注</text>
				</view>
				<view class="user_info_text" @click="gotoFollowers" :data-currentuid="userId">
					<text>{{ count_followers }}</text>
					<text>粉丝</text>
				</view>
			</view>
			
			<view class="user_button" v-if="is_followed">
				<view class="user_button_box user_unfollowed" @click="deleteFollower">
					<text>已关注</text>
					<u-icon name="checkbox-mark" color="#333" size="14px"></u-icon>
				</view>
			</view>
			<view class="user_button" @click="addFollower" v-else>
				<view class="user_button_box user_followed">
					<text>加关注+</text>
				</view>
			</view>
		</view>

		<view class="user_name_and_medal">
			<view class="user_name">
				<view class="dflex aib">
					<text class="f18 fbold">{{ userName }}</text>
				</view>
				<view class="dflex mt5 f14" v-if="user_ident_status == 10">
					<view class="dflex">
						<u-icon name="checkmark-circle-fill" color="primary" size="16"></u-icon>
						<text class="ml5 f14" style="color:#333;">{{ user_ident_name }}</text>
					</view>
				</view>
			</view>
			<!-- 
			<view class="user_medal">
				<image src="/static/metal.png" mode=""></image>
			</view> 
			-->
		</view>
		
		<view class="user_intro cflex">
			<view class="user_desc f14 fbold">
				<text v-if="showFullIntro == true" class="u-line-3">{{intro}}</text>
				<text v-else>{{intro}}</text>				
				<text v-if="moreButton == true" style="font-weight: normal; text-decoration: underline; font-size:12px" @click="fullIntro">更多...</text>
			</view>
			<view class="user_tag f12">
				<text>{{ tagYearSexConstellation }}</text>
			</view>
		</view>
		
		<view class="dflex wrap jcsb" v-if="user_ident_status == 10">
			<!-- 	<view class="dflex wrap_nt" v-if="loginCheck">		 -->
			<view class="cflex" @click="openMerchant">
				<view class="dflex aic">
					<u-icon name="home" color="#333" size="28"></u-icon>
					<text class="ml5 f14 mr5">团购</text>
					<u-icon name="arrow-right" color="#333" size="16"></u-icon>
				</view>
				<text class="f12">打开他的店铺</text>
			</view>
		</view>
		
		<u-sticky :customNavHeight="customNavHeight">
			<view class="wrap_ntb" style="background-color: #fff; padding: 0 0 5px 0;">
				<u-tabs 
					:list="memberList" 
					@click="clickMemberList"
					:activeStyle="{fontWeight: 'bold', transform: 'scale(1.05)'}"
					:inactiveStyle="{fontSize: '14px'}"
					lineWidth="25" 
					lineHeight="5" 
					lineColor="#FFD84A" 
				>
				</u-tabs>
			</view>
		</u-sticky>
		
		<view>
			<view class="waterfall-box h-flex-x h-flex-2">
				<view>
					<helang-waterfall 
						v-for="(item,index) in leftList" 
						:key="index" 
						:params="item" 
						tag="left"
						:index="index"
						@height="onHeight"
						@click="onClick"
					></helang-waterfall>
				</view>
				<view>
					<helang-waterfall 
						v-for="(item,index) in rightList" 
						:key="index" 
						:params="item" 
						@height="onHeight"
						@click="onClick"
						tag="right"
						:index="index"
					></helang-waterfall>
				</view>
			</view>
			<view class="load-txt">{{ajax.loadTxt}}</view>
		</view>
		
		<view class="empty_list" v-if="empty">				
			<u-empty mode="data" text="啥都没有~"></u-empty>
		</view>
		
		<u-popup :show="showBigavatar" @close="showBigavatar=false" mode="center" :safeAreaInsetBottom="false">
			<view class="dflex">
				<image :src="avatarSrc" mode="widthFix" :style="'width: 750rpx; height: ' + bigavatar + 'px;'"></image>
			</view>
		</u-popup>
		
		<bottomMenu></bottomMenu>
	</view>
</template>

<script>
	
	
	export default {
		data() {
			return {
				bgColor : "transparent",
				bannerSrc : '',
				avatarSrc : '',
				sysWidth : '',
				memberList : [{
                    name: '瞬间',
					type: 'topics'
                }, {
                    name: '收藏',
					type: 'collections'
                }, {
                    name: '点赞',
					type: 'likes'
                }],
				// 瀑布流
				leftHeight: 0,
				rightHeight: 0,
				leftList: [],
				rightList: [],
				ajax: {
					// 是否可以加载
					load: true,
					// 加载中提示文字
					loadTxt: '',
					// 每页的请求条件
					rows:10,
					// 页码
					page: 0,
				},
				// end 瀑布流
				topMenu : true,
				customNavHeight : '',
				userName : '',
				userId : '',
				intro : '',
				showFullIntro : true,
				moreButton : true,
				count_followers : '',
				count_followings : '',
				empty : false,
				loginCheck : true,
				//初始用户空间tab值，用来拼接请求地址的，很重要
				type : 'topics',
				uid : '',
				is_followed : false,
				tagYearSexConstellation : '',
				sex : '',
				birthday : '',
				animationData : {},
				showBigavatar : false,
				bigavatar : '',
				user_ident_merchant_id : '',
				user_ident_name : '',
				user_ident_status : ''
			}
		},
		onPageScroll(e) {
			// console.log('e',e)
			if(e.scrollTop > 135) {
				this.scrollMenu = true
				this.animation_menu('down')
				this.topMenu = false
			}
			if(e.scrollTop < 135) {
				this.scrollMenu = false
				this.animation_menu('up')
				this.topMenu = true
			}
			//根据scrollTop值超过某个临界点，设置不同的css样式
			// this.scrollTop = e.scrollTop;
		},
		onLoad:function(e) {
			//获取设备宽度，100%显示顶部banner
			var sys = uni.getSystemInfoSync()
			this.sysWidth = sys.screenWidth
			this.customNavHeight = sys.statusBarHeight + 43
			this.uid = e.uid
			this.user_check(e)			
			this.getStrangerInfo()			
			this.loadUserTopic();
			this.getFollowStatus();
		},
		// 触底触发
		onReachBottom() {
			if(this.loginCheck == true) {
				if (this.ajax.page <= this.total_page && this.total_page != 0) {
					this.loadUserTopic();
				}
			}
		},
		// 下拉刷新
		onPullDownRefresh(){
			// 正常情况下接口返回应该很会很快。故意延迟调用，让用户有在刷新的体验感
			setTimeout(()=>{
				this.ajax.page = 1;
				this.leftHeight = 0;
				this.rightHeight = 0;
				this.ajax.load = true;
				this.addList();
			},800);
		},
		methods: {	
			openBigAvatar() {
				this.showBigavatar = true
			},
			animation_menu(res) {			
				//创建动画
				var animation = uni.createAnimation({
					transformOrigin: "ease-in",
					duration: 300, //动画持续1秒
					// timingFunction: 'linear',  //linear 全程匀速运动
					// delay:300  //延迟两秒执行动画
				}) 
				this.animation = animation

				if(res == 'down') {
					animation.opacity(1).step()
				} else {
					animation.opacity(0).step()
				}
				
				this.animationData = animation.export()
			},
			getTagYearSexConstellation() {
				var memberYear = new Date(this.birthday).getFullYear();
				var memberMonth = new Date(this.birthday).getMonth() + 1;
				var memberDay = new Date(this.birthday).getDate();
				var sex = this.sex;
				
				var years = String(memberYear).substring(2,3)
				
				// console.log('ccccccccccccccc', memberYear,memberMonth,memberDay)
				
				if(sex == 1) {
					var sexual = '男生'
				} else {
					var sexual = '女生'
				}
				
				var name = "魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
				var arr2 = [20,19,21,21,21,22,23,23,23,23,22,22];
				var constellation = name.substr(memberMonth*2-(memberDay<arr2[memberMonth]?2:0),2);
			
				this.tagYearSexConstellation = years + '0后' + sexual + ' · ' + constellation + '座'
			},	
			noneClick() {},	
			gotoFollowings(e) {
				var uid = e.currentTarget.dataset.currentuid;
				// console.log(topicId);
				uni.navigateTo({
					url:"/pages/follow/followings?uid=" + uid,
				})
			},
			gotoFollowers(e) {
				var uid = e.currentTarget.dataset.currentuid;
				// console.log(topicId);
				uni.navigateTo({
					url:"/pages/follow/followers?uid=" + uid,
				})
			},
			user_check(e) {
				uni.showLoading({
					title:"加载中...."
				})
				uni.request({
					url:uni.getStorageSync('domain') + '/api/v1/user',
					method:'get',
					header: {
						'Accept': 'application/json',
						'Authorization' : 'Bearer ' + uni.getStorageSync('access_member_info').access_token
					},
					success: (res) => {						
						if(res.statusCode == 401) {
							this.loginCheck = false
							uni.removeStorageSync('access_member_info')
						}
						if(res.statusCode == 200 || res.statusCode == 201) {
							this.loginCheck = true
						}
						uni.hideLoading();
					},
					fail: (res) => {
					}
				})
			},
			openMerchant() {
				uni.navigateTo({
					url:"/packageShop/shop/shop?mid=" + this.user_ident_merchant_id
				})
			},
			getStrangerInfo() {				
				//初始列表
				uni.showLoading({
					title:"加载中...."
				})
				uni.request({
					url:uni.getStorageSync('domain') + '/api/v1/users/' + this.uid,
					method:'get',
					header: {
						'Accept': 'application/json',
						'Authorization' : 'Bearer ' + uni.getStorageSync('access_member_info').access_token
					},
					success: (res) => {
						// console.log('res1111111', res.data);
						this.userName = res.data.name
						this.userId = res.data.id
						this.intro = res.data.intro
						this.avatarSrc = res.data.avatar
						this.bannerSrc = res.data.banner
						this.sex = res.data.sex
						this.birthday = res.data.birthday
						this.count_followers = res.data.count_followers
						this.count_followings = res.data.count_followings
						this.user_ident_name = res.data.user_ident_name
						this.user_ident_status = res.data.user_ident_status
						this.user_ident_merchant_id = res.data.user_ident_merchant_id
						this.memberList[0].name  = '瞬间' + res.data.count_topics
						this.memberList[1].name  = '收藏' + res.data.count_collections
						this.memberList[2].name  = '点赞' + res.data.count_likes						
						this.getTagYearSexConstellation()
						uni.hideLoading();
					},
					fail: (res) => {
					}
				})
			},
			fullIntro() {
				this.showFullIntro = false
				this.moreButton = false 
			},
			gotoRegister() {
				uni.navigateTo({
					url:'/pages/register/register'
				})
			},			
			getFollowStatus() {
				if(this.loginCheck == true) {
					uni.showLoading({
						title: '加载中...',
						mask: true
					});
					uni.request({
						url:uni.getStorageSync('domain') + '/api/v1/users/followers_status/' + this.uid,
						method:'GET',
						header: {
							'Accept': 'application/json',
							'Authorization' : 'Bearer ' + uni.getStorageSync('access_member_info').access_token
						},
						success: (res) => {
							// console.log(res);
							if(res.data.status == 'followed') {
								this.is_followed = true
							}
							uni.hideLoading();
						},
						fail: (res) => {
						}
					})
				}
			},
			clickMemberList(e) {		
				//清空瀑布流
				let [left, right] = [
					[],
					[]
				];
				this.leftList = left;
				this.rightList = right;
				this.ajax.page = 0
				this.leftHeight = 0
				this.rightHeight = 0
				this.type = e.type
				this.loadUserTopic()
			},
			loadUserTopic() {
				uni.showLoading({
					title:"加载中...."
				})				
				uni.request({
					url: uni.getStorageSync('domain') + '/api/v1/user/' + this.uid + '/str' + this.type + '?page=' + (this.ajax.page + 1),
					// url: uni.getStorageSync('domain') + '/api/v1/topics',
					method: 'POST',
					success: res => {
						// console.log('loadIndexNew', res.data);
						// this.news = res.data;												
						if (res.data.meta.total == 0) {
							this.total_page = 0
							this.ajax.loadTxt = '';
							this.empty = true
							uni.hideLoading();
						} else {
							this.total_page = res.data.meta.last_page
							this.empty = false
							this.addList(res.data)
							this.ajax.page = res.data.meta.current_page
							if(res.data.meta.total < res.data.meta.per_page)								
							{
								this.ajax.loadTxt = '';
							}
							uni.hideLoading();
						}
						
						uni.hideLoading();
					},
					fail: () => {},
					complete: () => {}
				});
				
			},
			// 监听高度变化
			onHeight(height, tag) {
				if (tag == 'left') {
					this.leftHeight += height;
				} else {
					this.rightHeight += height;
				}
			},
			// 组件点击事件
			onClick(index, tag, e){
				var topicId = e.currentTarget.dataset.currentid;
				// console.log(topicId);
				uni.navigateTo({
					url:"/pages/article/article?TopicId=" + topicId
				})
			},
			// 获取数据
			addList(res) {		
				// 获取到的数据，请注意数据结构
				// console.log('addList', res)
				// console.log('addList_data_length',res.data.length);
				
				if(res.data.length < 1) {
					this.ajax.loadTxt = '没有更多了';
					return;
				}
			
				// 左右列表高度的差
				let differ = this.leftHeight - this.rightHeight;
				// 计算差值，用于确定优先插入那一边
				let differVal = 0;
								
				// 初始化左右列表的数据
				let i = differ > 0 ? 1 : 0;
				
				let [left, right] = [
					[],
					[]
				];
				
				
				// 获取插入的方向
				let getDirection = (index)=>{
					/* 左侧高度大于右侧超过 600px 时，则前3条数据都插入到右边 */
					if(differ>= 600 && index < 3){
						differVal = 1;
						return 'right';
					}
					
					/* 右侧高度大于左侧超过 600px 时，则前3条数据都插入到左边 */
					if(differ <= -600 && index < 3){
						differVal = -1;
						return 'left';
					}
					
					/* 左侧高度大于右侧超过 350px 时，则前2条数据都插入到右边 */
					if(differ >= 350 && index < 2){
						return 'right';
					}
					/* 右侧高度大于左侧超过 350px 时，则前2条数据都插入到左边 */
					if(differ <= -350 && index < 2){
						differVal = -1;
						return 'left';
					}
					
					/* 当前数据序号为偶数时，则插入到左边 */
					if ((i+differVal) % 2 == 0) {
						return 'left';
					} else {
						/* 当前数据序号为奇数时，则插入到右边 */
						return 'right';
					}
				}
				
				// 将数据源分为左右两个列表，容错差值请自行根据项目中的数据情况调节
				res.data.forEach((item, index) => {
					if(getDirection(index) == 'left'){
						//console.log(`差值：${differ},方向：left，序号${index}`)
						left.push(item);
					}else{
						//console.log(`差值：${differ},方向：right，序号${index}`)
						right.push(item);
					}
					i++;
				});				
				
				this.leftList = [...this.leftList, ...left];
				this.rightList = [...this.rightList, ...right];
				
				this.ajax.load = true;
				this.ajax.loadTxt = '加载中...';
				this.ajax.page++;
			},
			toProfile() {
				uni.navigateTo({
					url:"/pages/member/profile"
				})
			},
			addFollower() {
				if(this.loginCheck == true) {
					uni.showLoading({
						title: '加载中...',
						mask: true
					});
					uni.request({
						url:uni.getStorageSync('domain') + '/api/v1/users/followers/' + this.uid,
						method:'POST',
						header: {
							'Accept': 'application/json',
							'Authorization' : 'Bearer ' + uni.getStorageSync('access_member_info').access_token
						},
						success: (res) => {
							// console.log(res);
							this.is_followed = true
							uni.hideLoading()
						},
						fail: (res) => {
						}
					})
				} else {
					this.gotoRegister()
				}
			},
			deleteFollower() {
				if(this.loginCheck == true) {
					uni.showLoading({
						title: '加载中...',
						mask: true
					});
					uni.request({
						url:uni.getStorageSync('domain') + '/api/v1/users/followers/' + this.uid,
						method:'DELETE',
						header: {
							'Accept': 'application/json',
							'Authorization' : 'Bearer ' + uni.getStorageSync('access_member_info').access_token
						},
						success: (res) => {
							// console.log(res);
							this.is_followed = false
							uni.hideLoading()
						},
						fail: (res) => {
						}
					})
				} else {
					this.gotoRegister()
				}
			},
			gotoRegister() {
				uni.navigateTo({
					url:'/pages/register/register'
				})
			},
			autoBack() {
				uni.navigateBack({
					delta: 1,
				});
			},
		}
	}
</script>
<style lang="scss">
	page {
		background-color : #fff;
	}
</style>
<style lang="scss" scoped>	
	.shop_header_mask {
		background: #000;
		opacity: 0.3;
		display: flex;
		height: 180px;
		width: 750rpx;
	}
	.member_center {
		position: relative;
	}
	.member_banner {
		position: relative;
		z-index: 5;
	}
	.user_info_box {
		display: flex;
		position: relative;
		margin: -30px 12px 12px 12px;
		z-index: 7;
	}
	.user_avatar image {
		width: 70px;
		height: 70px;
		border-radius: 70px;
		border: 3px solid #fff;
	}
	.user_info {
		display: flex;
		align-items: flex-end;
	}
	.user_info_text {
		display: flex;
		flex-direction: column;
		margin-left: 10px;
	}
	.user_info_text text:nth-child(1) {
		font-size: 16px;
		font-weight: bold;
	}
	.user_info_text text:nth-child(2) {
		font-size: 14px;
		color: #A8A8A8;
	}
	.user_button {
		display: flex;
		align-items: flex-end;
		flex-grow: 1;
		margin-left: 25px;
		font-size: 12px;
		justify-content: flex-end;
	}
	.user_button_box {
		display: flex;
		border-radius: 50px;
		background-color: #FAFAFA;
		border: 2px solid #333;
		height: 30px;
		padding: 0 10px;
		margin: 0 5px;
		align-items: center;
		justify-content: center;
	}
	.user_name_and_medal {
		display: flex;
		justify-content: space-between;
		margin: 20px 12px 10px 12px;
	}
	.user_name {
		display: flex;
		flex-direction: column;
	}
	.user_name text:nth-child(1) {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 5px;
	}
	.user_name text:nth-child(2) {
		font-size: 12px;
		color: #999;
	}
	.user_medal image {
		width: 50px;
		height: 50px;
	}
	.user_intro {
		margin: 0 12px 5px 12px;
	}
	.user_tag {
		margin-top: 10px;
	}
	.user_tag text {
		background-color: #FAFAFA;
		padding: 2px 10px;
		border-radius: 50px;
	}
	.home_tab {
		background: #fff;
	}
	.waterfall-box {
		padding: 20rpx 10rpx;
		box-sizing: border-box;
	
		>view {
			padding: 0 10rpx;
		}
	}	
	.h-flex-x {
		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
		justify-content: flex-start;
		align-items: flex-start;
		align-content: flex-start;
	
		&.h-flex-2 {
			>view {
				width: 50%;
			}
		}
	}	
	.load-txt{
		padding: 0 0 20rpx 0;
		text-align: center;
		color: #999;
		font-size: 24rpx;
	}
	.user_followed {
		border: 2px solid #333;
		background: #ffd84a;
	}
	.user_unfollowed {
		border: 2px solid #333;
		background: #eee;
	}
	.member_scroll {
		width: 100%;
		position: fixed;
		opacity: 0;
		top: 0;
		z-index: 10;
	}
</style>
